package com.example.android.apis;



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseAdapter
{
	public static final String KEY_TITLE = "title";
	public static final String KEY_BODY = "body";
	public static final String KEY_ROWID = "_id";//convention to have "_" before
	
	public static final String TAG = "DataAdapter";
	private SQLiteDatabase mDB;
	private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement," +
			"title text not null, body text not null);";
	private final static String DB_NAME = "notepad";
	private final String DB_TABLE = "notes";
	private static final int DB_VERSION = 2;
	private final Context mCtx;
	private DatabaseHelper mDBHelper;
	
	
	private static class DatabaseHelper extends SQLiteOpenHelper
	{
		DatabaseHelper(Context context)
		{
			super(context, DB_NAME , null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) 
		{
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) 
		{
			Log.v(TAG," Database Version is being updated, all data will be lost");
			db.execSQL("DROP TABLE IF EXITS notes");
			onCreate(db);			
		}
	}
	
	public DatabaseAdapter(Context ctx)
	{
		this.mCtx = ctx;
	}
	
	public DatabaseAdapter open() throws SQLException
	{
		 mDBHelper = new DatabaseHelper(mCtx);
		 mDB = mDBHelper.getReadableDatabase();
		 return this;
	}
	
	public void close()
	{
		mDBHelper.close();
	}
	public long createNote(String title, String body)
	{
		ContentValues initialize = new ContentValues();
		initialize.put(KEY_TITLE, title);
		initialize.put(KEY_BODY, body);
		return mDB.insert(DB_TABLE, null, initialize);
	}
	public boolean deleteNote(long rowID)
	{
		return mDB.delete(DB_TABLE, KEY_ROWID + "=" +rowID, null)>0;//mDB.delete returns how many rows it has returned.
	}
	
	public boolean updateNote(long rowID, String title, String body)
	{
		ContentValues args = new ContentValues();
		args.put(KEY_TITLE, title);
		args.put(KEY_BODY, body);
		return mDB.update(DB_TABLE, args, KEY_ROWID + "="+rowID, null)==1;
	}
	
	public Cursor getAllNotes()
	{
		Cursor mCursor = mDB.query(true, DB_TABLE, new String[]{KEY_ROWID, KEY_TITLE}, null,null,null,null,null,null);
		if(mCursor != null)
			mCursor.moveToFirst();
		
		return mCursor;
	}
	
	public Cursor getNote(long rowId){
		Cursor mCursor = mDB.query(true, DB_TABLE, new String[]{KEY_ROWID, KEY_TITLE}, KEY_ROWID+"="+rowId,null,null,null,null,null);
		if(mCursor != null)
			mCursor.moveToFirst();
		
		return mCursor;

	}
	
}
